<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://raw.githubusercontent.com/axios/axios/v1.x/dist/axios.js"></script>
</head>
<body>
  <div>版本更新</div>
  <br/>
  <button onclick="checkUpdate()">检查更新</button>
  <script>
    function compareVersion(serverVersion){
      return new Promise((resolve, reject) => {
        window.chcp.getVersionInfo((error, data) => {
          console.log('getVersionInfo', data);
          if (error) {
            reject(error)
          } else {
            resolve(data.currentWebVersion === serverVersion);
          }
        });
      });
    }
    function checkUpdate() {
      const url = "https://yourserver/chcp.json";
      axios({
        url:url,
        methods: 'get'
      }).then(res => {
        const data = res.json();
        const isEqual = compareVersion(data.release)
        if (isEqual) {
          toast('已是最新版');
        } else {
          // 流程2，检查是否有可安装更新
          checkAvalilable();
        }
      }).catch((error) => {
        console.log('checkUpdate failed', error)
      });
    }
    function checkAvalilable() {
      console.log('checkAvalilable');
      window.chcp.isUpdateAvailableForInstallation((error, data) => {
        if (error) {
          console.log('isUpdateAvailableForInstallation error', error);
          checkHotUpdate();
          return;
        }
        // 已有可安装版本
        beforeInstallAlert();
      });
    }
    // 获取更新
    function checkHotUpdate() {
      console.log('checkHotUpdate');
      const waitingId = setTimeout(() => {
        toast('有新版，开始更新');
      }, 200);
      window.chcp.fetchUpdate((error, data) => {
        if (error) {
          console.log('fetchUpdate error', error);
          clearTimeout(waitingId);
          if (error.code == 2) {
            toast('已是最新版');
          } else if (error.code == -17) {
            toast('正在下载更新中...');
          } else if (error.code == -2) { 
            // 需要下载apk
          } else {
            toast(`出错了: ${error.code}`);
          }
          return;
        }
        // 服务器版本信息
        console.log('fetchUpdate data', data);
        // JSON解析config
        const config = data && data.config && JSON.parse(data.config);
        console.log('fetchUpdate config', config);
        // 下载完成，message为自定义字段，表示更新内容
        beforeInstallAlert(config && config.message);
      });
    }

    function beforeInstallAlert(message) {
      // 弹窗逻辑，点击“立即体验”调用installUpdate()
    }

    function installUpdate() {
      console.log('installUpdate');
      window.chcp.installUpdate((error) => {
        if (error) {
          console.log('installUpdate error', error);
          toast(`安装失败: ${error.code}`);
          return;
        }
        console.log('installUpdate done');
      });
    }
  </script>
</body>
</html>